/**
 * 
 */
package com.vision.admin.sv.serv;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.vision.core.cm.db.data.ActivityLog;
import com.vision.core.sv.db.CustomSessionFactoryBean;
import com.vision.core.sv.db.mgr.DataManager;

/**
 * @author Mark
 * 
 */
public class PrintLogsServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	private static final Logger log = LoggerFactory.getLogger(PrintLogsServlet.class);

	private static final String LINE_PATTERN = "%-10s | %-25s | %-15s | %-15s | %-15s | %-50s\r\n";
	private static final String HEADER_SEPARATOR = "-------------" +
			"----------------------------" +
			"------------------" +
			"------------------" +
			"------------------" +
			"--------------------------------------------------\r\n";

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		log.info("Processing request to print logs...");

		DataManager<ActivityLog> logManager = new DataManager<ActivityLog>() {
			@Override
			public Class<ActivityLog> getManagedClass() {
				return ActivityLog.class;
			}
		};
		logManager.setSessionFactory(CustomSessionFactoryBean.getFactory());

		List<ActivityLog> activityLogs = logManager.getTemplate().find("FROM " + ActivityLog.class.getName() + " ORDER BY timestamp DESC");
		StringBuilder sb = new StringBuilder(activityLogs.size() * 500);
		
		sb.append(String.format(LINE_PATTERN , "ID", "Timestamp", "Username", "Domain", "Type", "Detail"));
		sb.append(HEADER_SEPARATOR);
		for (ActivityLog al : activityLogs) {
			sb.append(String.format(LINE_PATTERN, al.getId(), al.getTimestamp(),
												al.getUser().getUsername(), al.getDomain(),
												al.getType(), al.getSerializedString()));
		}
		
		String message = sb.toString();
		
		resp.setContentType("application/text");
		resp.setContentLength( message.getBytes().length );
		resp.setHeader("Content-Disposition", "attachment; filename=\"logs.txt\"");

		ServletOutputStream os = resp.getOutputStream();
		PrintWriter w = new PrintWriter(os);
		w.write(message);
		w.flush();
		w.close();

		os.flush();
		os.close();
	}

}
